package com.qianxx.view.loadingview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by Administrator on 2017/11/7.
 */
public class BallLoading extends View {

    private int mRadius;
    private Paint mPaint;
    private int mWidth;
    private int mHeight;
    private double mAngle = 0;

    public BallLoading(Context context) {
        this(context, null);
    }

    public BallLoading(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BallLoading(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setColor(Color.WHITE);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        mWidth = w / 2;
        mHeight = h / 2;
        mRadius = w / 10;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (mAngle > 360) {
            mAngle = mAngle - 360;
        } else {
            mAngle += 45;
        }

        canvas.translate(mWidth, mHeight);
        canvas.rotate((float) mAngle);

        for (int i = 0; i < 8; i++) {
            PointF pointF = circleAt(mRadius, i * (Math.PI / 4));
            canvas.drawCircle(pointF.x, pointF.y, 24 - i * 2, mPaint);
        }

        postInvalidateDelayed(50);
    }

    public void show(boolean show) {
        if (show) {
            setVisibility(VISIBLE);
        } else {
            setVisibility(View.GONE);
        }
    }

    private PointF circleAt(float radius, double angle) {
        float x = (float) (radius * Math.sin(angle));
        float y = (float) (radius * Math.cos(angle));
        return new PointF(x, y);
    }
}
